package org.HisCanvas.ChrisRiffle.JFlightLog.persist;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBook;
import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBookRec;
import org.HisCanvas.ChrisRiffle.JFlightLog.logging.LogController;



public class LogBookDaoJpa implements LogBookDAO, LogBookDbConstants {

	
	public static final String JFLIGHTLOG_DB_JPA_NAME = "jflightlogDB";
	
	private static EntityManager em;
	
		
	/**
	 * inits entity manager
	 */
	public void init() throws Exception{
					
		LogController.info("Getting JPA entity manager");
		
		if(em == null){
			
			em = Persistence.createEntityManagerFactory(JFLIGHTLOG_DB_JPA_NAME).createEntityManager();	
		}
				
	}
	
	
	/**
	 * closes entity manager
	 */
	public void close() throws Exception{
				
		em.getEntityManagerFactory().close();
		em.close();
	}
	
	
	
	/**
	 * Gets the etire logbook
	 * 
	 * @return
	 */
	public LogBook getLogBook() throws Exception {
						
		LogBook rLogBook = new LogBook();
		
		final List<LogBookRec> recList = (List<LogBookRec>)em.createQuery("select r from LogBookRec r")
        	.getResultList();

		rLogBook.getLogBookRecList().addAll(recList);
		
		return rLogBook;
	}


	/**
	 * Gets
	 * 
	 * @return
	 */
	public LogBookRec getLogBookRec(int pPkId) throws Exception {
		
		final List<LogBookRec> recList = em.createQuery(
				"select r from LogBookRec r WHERE r.primaryKey = " + pPkId)
				.getResultList();

		if (recList.size() > 1) {
			String msg = "pkey not unique(multiple recs with key): " + pPkId;
			LogController.severe(msg);
			throw new Exception(msg);
		}

		return recList.get(0);
	}


	/**
	 * addLogBookRec
	 * 
	 * @param pLogBookRec
	 */
	public void addLogBookRec(LogBookRec pLogBookRec) throws Exception{
				
		em.getTransaction().begin();
		
		em.persist(pLogBookRec);	
						
		em.getTransaction().commit();
		
		
	}
	
	
	/**
	 * NOte the rec must have a primary key
	 * 
	 * 
	 */
	public void modifyLogBookRec(LogBookRec pLogBookRec) throws Exception{
				
		em.getTransaction().begin();
		
		LogBookRec retrievedRecEntity = em.find(LogBookRec.class, pLogBookRec.getPrimaryKey());
				
		em.persist(retrievedRecEntity);	
						
		em.getTransaction().commit();	
	}
	
	
	/**
	 * deleteLogBookRec
	 * 
	 * @param pLogBookRec
	 */
	public void removeLogBookRec(LogBookRec pLogBookRec) throws Exception{
		
		em.getTransaction().begin();
		
		em.remove(pLogBookRec);			
		
		em.getTransaction().commit();
				
	}
	
	
}


